var bodyParser = require('body-parser')
var urlencodedParser = bodyParser.urlencoded({
    extended: false
})
var express = require('express')
var db = require('../db.js')
var md5 = require('md5-nodejs')
var multer = require('multer');
var router = express.Router()

// 渲染列表
router.get('/list', async function (req, res) {
    var {
        currentPage,//当前页
        pageSize, //每页多少
        searchVal,
        orderby,//通过方式
        sort,//正序 or 倒序
    } = req.query;
    if (!currentPage) {
        currentPage = 1
    }

    if (!pageSize) {
        pageSize = 20
    }

    // 查数据
    var sql = `select m.id,m.title,m.content,m.author,m.cid,m.time,m.date,c.name as type 
        from msbd as m,classify as c where m.cid=c.id `

    // 查总数
    var sql_count = "select count(*) as total from msbd as m,classify as c where m.cid=c.id";

    var num = currentPage * pageSize;//总条数
    if (searchVal) {
        sql_count += `  and title like '%${searchVal}%'`;
        sql += `  and m.title like '%${searchVal}%'`;
    }
    if (orderby) {
        sql += `  order by ${orderby} ${sort}`;
    }

    sql += `  limit ${num},${pageSize}`
    const data = await Promise.all([db.doSQL(sql), db.doSQL(sql_count)])
    res.send(db.handleResults(data[0].data, data[1].data[0].total))
})

// 新增
router.post('/addList', urlencodedParser, async function (req, res) {
    var {
        title,
        content,//内容
        author,
        cid,  //类别
        time
    } = req.body
    var sql = `insert into msbd (title, content, author, cid, time) values ("${title}","${content}","${author}","${cid}","${time}")`
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handleResults(data))
})

// 修改
router.post('/updateList', urlencodedParser, async function (req, res) {
    var {
        id,
        title,
        content,
        author,
        cid,
        time
    } = req.body
    var sql = `update msbd set title='${title}',content="${content}",author='${author}',cid='${cid}',time='${time}' where id='${id}'`
    const {
        data
    } = await db.doSQL(sql)
    res.send(db.handleResults(data))
})

// 删除
router.get('/delList', async function (req, res) {
    var ids = req.query.id
    var sql = `delete from msbd where id in (${ids})`
    const data = await db.doSQL(sql)
    res.send(db.handleResults(data))
})

// 获取已读的msbd的id
router.get('/get-bdids-byUid', async function (req, res) {
    var { uid } = req.query
    var sql = `select bdid from study where uid=${uid}`
    const { data } = await db.doSQL(sql)
    let idsArr = data.map(v => v.bdid)
    res.send(db.handleResults(idsArr))
})



module.exports = router;